package com.hcss.common.util;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.HexUtil;
import com.hcss.picture.constant.PictureConstant;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class ImageColorUtil {

	/**
	 * 获取占比最高的颜色及其占比
	 *
	 * @param file 图片文件
	 * @param num  返回颜色数量
	 * @return <颜色,<数量,比例>>
	 */
	public static Map<String, Pair<Integer, Double>> colorRate( File file,int num ) {
		Map<String, Pair<Integer, Double>> result = new HashMap<>();
		int[] rgb = new int[3];
		BufferedImage bi = null;

		try {
			bi = ImageIO.read(file);
		} catch (IOException e) {
			log.error("read_img_fail", e);
		}

		if (bi == null) {
			return result;
		}

		int width = bi.getWidth();
		int height = bi.getHeight();
		int minx = bi.getMinX();
		int miny = bi.getMinY();


		int total = width * height;
		for (int i = minx; i < width; i++) {
			for (int j = miny; j < height; j++) {
				int pixel = bi.getRGB(i, j);
				rgb[0] = (pixel & 0xff0000) >> 16;
				rgb[1] = (pixel & 0xff00) >> 8;
				rgb[2] = (pixel & 0xff);

				String color = String.join("", "#", HexUtil.toHex(rgb[0]), HexUtil.toHex(rgb[1]), HexUtil.toHex(rgb[2])).toUpperCase();
				if (result.containsKey(color)) {
					Pair<Integer, Double> numRate = result.get(color);
					result.put(color, new Pair<>(numRate.getKey() + 1, (numRate.getKey() + 1) * 1.0 / total));
				} else {
					result.put(color, new Pair<>(1, 0.0));
				}

			}
		}

		return result.entrySet().stream()
				.sorted(Map.Entry.comparingByValue((v1, v2) -> v2.getKey().compareTo(v1.getKey()))).limit(num)
				.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, LinkedHashMap::new));

	}

	public static void main(String[] args) {
		File file = new File("D:\\毕设资料\\pictures\\关键代码\\java端调用模型.png");
		Map<String, Pair<Integer, Double>> stringPairMap = colorRate(file, 10);
		Pair< Integer, Double > integerDoublePair=stringPairMap.get( PictureConstant.COLOR_WHITE );
		Double value=integerDoublePair.getValue( );
		System.out.println((value*100+"").substring( 0,5 )+"%" );
		System.out.println(stringPairMap);
	}

}
